#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using UnityEditor;
using DICE_GS;

public class ExportManager : MonoBehaviour
{

    private static ExportManager instance = null;
    public static ExportManager Instance
    {
        get
        {
            if (instance == null)
            {
                glog.debug("instantiate");
                GameObject go = new GameObject();
                instance = go.AddComponent<ExportManager>();
                go.name = "ExportManager";
            }

            return instance;
        }
    }

    // z-order ?�치 �?�� 간격
    static float z_order_offset = 0.01f;

    static float start_x = 0;
    static float start_y = 0;

    public static List<BoardTile> pathTemp = new List<BoardTile>();
    public static List<MultiListPath> paths = new List<MultiListPath>();
    static Dictionary<int, BoardTile> boardDic = new Dictionary<int, BoardTile>();
    static BoardTile startBoard = null;
    static GameObject emptyParent;
    // Use this for initialization
    static bool isCheckPathStarted;

    public static Dictionary<string, BoardInfo.TileEffectType> tileEffectMap = new Dictionary<string, BoardInfo.TileEffectType>()
	{
		{"teleport_to_tile" , BoardInfo.TileEffectType.TeleportToTile},	
		{"modify_tile_height" , BoardInfo.TileEffectType.ModifyTileHeight},	
		{"modify_tile_condition" , BoardInfo.TileEffectType.ModifyTileCondition},	
		{"set_tile_effect" , BoardInfo.TileEffectType.SetTileEffect},	
		{"get_stop_effect" , BoardInfo.TileEffectType.GetStopEfffect},	
		{"modify_team_param" , BoardInfo.TileEffectType.ModifyTeamParam},	
		{"teleport_to_player" , BoardInfo.TileEffectType.TeleportToPlayer},
		{"teleport_switch" , BoardInfo.TileEffectType.TeleportSwitch},
		{"event_jump" , BoardInfo.TileEffectType.EventJump},
		{"move_extend" , BoardInfo.TileEffectType.MoveExtend},
		{"heal" , BoardInfo.TileEffectType.Heal},
		{"damage" , BoardInfo.TileEffectType.Damage},
		{"resurrect" , BoardInfo.TileEffectType.Resurrect},
		{"bind" , BoardInfo.TileEffectType.Bound},
		{"add_item_temp" , BoardInfo.TileEffectType.AddItem},
		{"loot_item_temp" , BoardInfo.TileEffectType.LootItem},
		{"ignore_pass_effect" , BoardInfo.TileEffectType.IgnorePassEffect},
		{"spawn_decoy" , BoardInfo.TileEffectType.SpawnDecoy},
		{"spawn_trap" , BoardInfo.TileEffectType.SpawnTrap},
		{"spawn" , BoardInfo.TileEffectType.Spawn},
		{"dice_delete" , BoardInfo.TileEffectType.DiceDelete},
		{"dice_add" , BoardInfo.TileEffectType.DiceAdd},
		{"dice_switch" , BoardInfo.TileEffectType.DiceSwitch},
		{"sleep" , BoardInfo.TileEffectType.Sleep},
		{"extra_turn" , BoardInfo.TileEffectType.ExtraTurn},
		{"abnormal_delete" , BoardInfo.TileEffectType.AbnormalDelete},
		{"abnormal_dispell" , BoardInfo.TileEffectType.AbnormalDispell},
		{"case_mp_recover" , BoardInfo.TileEffectType.CaseMPRecover},
		{"random_effect" , BoardInfo.TileEffectType.RandomEffect},
        {"spawn_boss", BoardInfo.TileEffectType.SpawnBoss},
	};

    void Start()
    {

    }

    //	[MenuItem("TheDice/Import_map_prototype")]
    //	public static void ImportMap_proto()	
    //	{
    //		TextAsset textAsset = (TextAsset) AssetDatabase.LoadAssetAtPath("Assets/TheDice/TextAsset/map_prototype.txt", typeof(TextAsset) );
    //		ImportMap(textAsset);
    //	}
    //
    //	[MenuItem("TheDice/Import_map_demo01")]
    //	public static void ImportMap_demo01()	
    //	{
    //		TextAsset textAsset = (TextAsset) AssetDatabase.LoadAssetAtPath("Assets/TheDice/TextAsset/map_demo01.txt", typeof(TextAsset) );
    //		ImportMap(textAsset);
    //	}
    //
    //	[MenuItem("TheDice/Import_map_demo02")]
    //	public static void ImportMap_demo02()	
    //	{
    //		TextAsset textAsset = (TextAsset) AssetDatabase.LoadAssetAtPath("Assets/TheDice/TextAsset/map_demo02.txt", typeof(TextAsset) );
    //		ImportMap(textAsset);
    //	}
    //	
    //	[MenuItem("TheDice/Import_map_m1_1")]
    //	public static void ImportMap_m1_1()	
    //	{
    //		TextAsset textAsset = (TextAsset) AssetDatabase.LoadAssetAtPath("Assets/TheDice/TextAsset/map_m1_1.txt", typeof(TextAsset) );
    //		ImportMap(textAsset);
    //	}	

	public static void ImportMapName(string mapName, element elementType)
    {
        //		string assetPath = "Assets/TheDice/TextAsset/map_" + mapName + ".txt";
        //		TextAsset textAsset = (TextAsset) AssetDatabase.LoadAssetAtPath(assetPath, typeof(TextAsset) );
        //ImportMap_old(textAsset);

		ImportMap("map_" + mapName, elementType);
    }

    public static void ImportMiniMapName(string mapName)
    {
        //		string assetPath = "Assets/TheDice/TextAsset/map_" + mapName + ".txt";
        //		TextAsset textAsset = (TextAsset) AssetDatabase.LoadAssetAtPath(assetPath, typeof(TextAsset) );
        //ImportMap_old(textAsset);

        ImportMapForMiniMap("map_" + mapName);
    }

	public static void ImportMap(string mapName, element elementType)
    {
		string[,] lines = LoadMapLaout.MapLayout(mapName);

		// temporarily
		string commonRoadName = "tile_road_common";
		tk2dSpriteCollectionData collectionData;
		if(elementType != element.none)
		{
			commonRoadName += string.Format("_"+elementType.ToString() );
			GameObject tmp = Resources.Load("Prefabs/Map_theme/"+elementType.ToString() ) as GameObject;
			collectionData = tmp.GetComponent<SpriteResManager>().collection;
		}
		else
		{
			GameObject tmp = Resources.Load("Prefabs/Map_theme/normal") as GameObject;
			collectionData = tmp.GetComponent<SpriteResManager>().collection;
		}

        //Object prefabTile = AssetDatabase.LoadAssetAtPath("Assets/TheDice/Prefabs/BoardTile.prefab", typeof(GameObject));	
        Object prefabTile = Resources.Load("Prefabs/Ingame/BoardTileNew") as GameObject;
        float initial_x = start_x;
        float initial_y = start_y;
        float tile_x = initial_x;
        float tile_y = initial_y;
        float tile_z = 0;
        int id_count = 1;

//		GameObject startTilePosGo = Resources.Load("Prefabs/BoardStartTilePos/StartTilePos_"+ mapName) as GameObject;
//		StartTilePosInfo startPosInfo = null;
//		if(startTilePosGo!=null)
//			startPosInfo = startTilePosGo.GetComponent<StartTilePosInfo>();

        //string[,] grid = CSVReader.SplitCsvGrid(textAsset.text);

        //int maxGridX = grid.GetUpperBound(0);

        //glog.debug ("bound x="+maxGridX);	
        //glog.debug ("bound y="+grid.GetUpperBound(1));		
		glog.debug("ImportMap " + mapName+ "   "+elementType.ToString());
        boardDic.Clear();
        emptyParent = null;
        PathManager pathManager = null;
        bool bAlreadyBoardCreated = false;
        GameObject pathMgrObj = GameObject.FindGameObjectWithTag("Path Manager");
        if (pathMgrObj != null)
        {
            bAlreadyBoardCreated = true;
            pathManager = pathMgrObj.GetComponent<PathManager>();
            emptyParent = pathMgrObj.transform.parent.gameObject;
        }
        else
        {
            emptyParent = new GameObject();
			if(elementType != element.none)
				emptyParent.name = mapName + string.Format("_"+elementType.ToString() );
			else
				emptyParent.name = mapName;
			
			GameObject go = new GameObject();
            pathManager = go.AddComponent<PathManager>();
            go.name = "PathManager";
            go.tag = "Path Manager";
            go.transform.parent = emptyParent.transform;

        }
        //string [] lines =   textAsset.text.Split("\n"[0]); 
        glog.debug(" upperbound  " + lines.GetUpperBound(0) + "    " + lines.GetUpperBound(1));

        //pathManager.nMaxY = lines.GetUpperBound(1) + 2;
        pathManager.nMaxY = 1;
        int maxGridX = 0;

		BoardTile startTile = null;
		BoardTile goalTile = null;
		//int tile_z_y_inc=0;
        for (int y = lines.GetUpperBound(1); y >= 0; y--)
        {
			//tile_z = tile_z_y_inc++;
            bool bHasValue = false;
            for (int x = 0; x <= lines.GetUpperBound(0); x++)
            {

                if (lines[x, y] != null && lines[x, y] != "")
                {
                    bHasValue = true;
                    break;
                }
            }
            if (bHasValue)
            {
                pathManager.nMaxY++;
                if (lines.GetUpperBound(0) + 1 > maxGridX)
                    maxGridX = lines.GetUpperBound(0) + 1;

                for (int x = 0; x <= lines.GetUpperBound(0); x++)
                {
                    string strTile = lines[x, y];
                    //if(y==0)
                    //	glog.debug("strTile="+strTile);
					if (strTile != null && strTile != "" && strTile != " " && strTile != "  " && strTile != "   " && strTile != "    ")
                    {
                        GameObject tileObj = null;
                        BoardInfo boardInfo = null;

                        if (bAlreadyBoardCreated)
                        {
                            foreach (Transform child in emptyParent.transform)
                            {
                                BoardTile bt = child.gameObject.GetComponent<BoardTile>();
                                if (bt != null && bt.boardInfo.id == id_count)
                                {
                                    tileObj = bt.gameObject;
                                    tileObj.GetComponent<BoardTile>().boardInfo.Clear();
                                    break;
                                }
                            }
                        }
                        else
                        {
                            tileObj = Instantiate(prefabTile) as GameObject;
							tileObj.AddComponent<tk2dSprite>();
                            boardInfo = tileObj.GetComponent<BoardTile>().boardInfo;
                            boardInfo.pathInfo.Add(new PathInfo());
                            boardInfo.pathInfo.Add(new PathInfo());

                        }

                        tileObj.name = "BoardTile_" + id_count.ToString();
						if (!bAlreadyBoardCreated)
                        	tileObj.transform.position = new Vector3(tile_x, tile_y, tile_z);
                        boardInfo = tileObj.GetComponent<BoardTile>().boardInfo;
                        boardDic.Add(id_count, tileObj.GetComponent<BoardTile>());
                        pathManager.boardCount = id_count;
                        boardInfo.id = id_count++;
                        boardInfo.index_x = x + 1;
                        boardInfo.index_y = y + 1;
						boardInfo.x=tile_x;
						boardInfo.y=tile_y;
						boardInfo.z=tile_z;

                        tileObj.transform.parent = emptyParent.transform;



                        tk2dSprite sprite = tileObj.GetComponent<tk2dSprite>();
						sprite.renderer.sortingLayerName = "Board";
						sprite.SetSprite( collectionData, commonRoadName);
						float scaleMod = 0.1f;
						sprite.scale = new Vector3(scaleMod,scaleMod,scaleMod);
                        sprite.color = new Color(255, 255, 255, 255);
                        string trimedStr = strTile.Trim(new char[] { '\"', ' ', '\r' });

						
						string[] commandToken = trimedStr.Split(';');

                        string tilename = commandToken[0];

                        boardInfo.tilename = CBoardDataManager.Instance.GetBoardType(tilename);
                        if (boardInfo.tilename == BoardInfo.TileName.None)
                        {
                            if (y == 0)
                            {
                                tilename = tilename.Remove(tilename.Length - 1);
                                boardInfo.tilename = CBoardDataManager.Instance.GetBoardType(tilename);
                                if (boardInfo.tilename == BoardInfo.TileName.None)
                                    Debug.LogError("tilename none  " + tilename + "  x=" + (x + 1) + "  y=" + (y + 1));
                            }
                            else
                                Debug.LogError("tilename none  " + tilename + "  x=" + (x + 1) + "  y=" + (y + 1));
                        }

                        if (commandToken.Length > 1)
                        {
							string commandStr = commandToken[1].Trim(new char[] { ' ', '\r' });
							if(y==0)
							{
								string lastStr = commandStr.Remove(0,commandStr.Length-1);
								glog.debug(x+"   lastStr="+lastStr);
								int num;
								bool parsed = int.TryParse( lastStr , out num);
								if (parsed)
								{
									commandStr = commandStr.Remove (commandStr.Length-1);
								}
							}
							boardInfo.command = commandStr;
                            string[] tokens = boardInfo.command.Split(new char[] { '(', ',', ')' });
                            ParseTokens(boardInfo, tokens);
                        }

                        //for several modify_team_param parse twice
                        if (commandToken.Length > 2)
                        {
                            string cmd = commandToken[2].Trim(new char[] { ' ', '\r' });
                            string[] tokens = cmd.Split(new char[] { '(', ',', ')' });
                            ParseTokens(boardInfo, tokens);
                        }

                        if (tilename.StartsWith("road_start"))
                        {
                            boardInfo.isStart = true;
                            startBoard = tileObj.GetComponent<BoardTile>();
							startTile = startBoard;
                            Vector3 camPos = Camera.main.transform.position;
                            camPos.x = tile_x;
                            camPos.y = tile_y;
                            Camera.main.transform.position = camPos;
//							if(startPosInfo!=null)
//								tileObj.transform.position = startPosInfo.GetPos(true, elementType, tileObj.transform.position);
                        }
                        else if (tilename.StartsWith("road_end") || tilename.StartsWith("road_goal"))
                        {
                            boardInfo.isGoal = true;
							goalTile = tileObj.GetComponent<BoardTile>();
//							if(startPosInfo!=null)
//								tileObj.transform.position = startPosInfo.GetPos(false, elementType, tileObj.transform.position);
                        }

						boardInfo.tilenameStr = BoardTile.SetModelName(sprite, boardInfo.tilename, elementType);

                        tile_z += z_order_offset;

                    }
                    else
                    {
                        //pathManager.boartTiles[x,y] = null;
                    }

                    //tile_x += 0.295819f;  // for height 720
                    //tile_y += 0.150303f;  // for height 720

                    tile_x += 0.294887f;
                    tile_y += 0.1500896f;
                }

                initial_x += -0.294887f;
                initial_y += 0.1500896f;
                tile_x = initial_x;
                tile_y = initial_y;
            }


        }

        pathManager.nMaxX = maxGridX + 1;
        //glog.debug ("pathMrg board: "+pathManager.boartTiles.GetUpperBound(0)+" "+pathManager.boartTiles.GetUpperBound(1) );
        glog.debug("total created=" + (id_count - 1));


		int index_dx_start = 0;
		int index_dy_start = 0;
		int index_dx_goal = 0;
		int index_dy_goal = 0;
		foreach (Transform child in emptyParent.transform)
		{
			BoardTile bt = child.gameObject.GetComponent<BoardTile>();
			if(bt==null)
				continue;
			if(startTile!=null)
			{
				if(bt.boardInfo.index_x == startTile.boardInfo.index_x+1 && bt.boardInfo.index_y== startTile.boardInfo.index_y)
					index_dx_start = 1;
				if(bt.boardInfo.index_y == startTile.boardInfo.index_y+1 && bt.boardInfo.index_x== startTile.boardInfo.index_x)
					index_dy_start = 1;
				if(bt.boardInfo.index_x == startTile.boardInfo.index_x-1 && bt.boardInfo.index_y== startTile.boardInfo.index_y)
					index_dx_start = -1;
				if(bt.boardInfo.index_y == startTile.boardInfo.index_y-1 && bt.boardInfo.index_x== startTile.boardInfo.index_x)
					index_dy_start = -1;
			}
			if(goalTile!=null)
			{
				if(bt.boardInfo.index_x == goalTile.boardInfo.index_x+1 && bt.boardInfo.index_y== goalTile.boardInfo.index_y)
					index_dx_goal = 1;
				if(bt.boardInfo.index_y == goalTile.boardInfo.index_y+1 && bt.boardInfo.index_x== goalTile.boardInfo.index_x)
					index_dy_goal = 1;
				if(bt.boardInfo.index_x == goalTile.boardInfo.index_x-1 && bt.boardInfo.index_y== goalTile.boardInfo.index_y)
					index_dx_goal = -1;
				if(bt.boardInfo.index_y == goalTile.boardInfo.index_y-1 && bt.boardInfo.index_x== goalTile.boardInfo.index_x)
					index_dy_goal = -1;
			}
		}
		if(startTile!=null)
			BoardTile.SetStartGoalTilePos(elementType, startTile, index_dx_start, index_dy_start);
		if(goalTile!=null)
			BoardTile.SetStartGoalTilePos(elementType, goalTile, index_dx_goal, index_dy_goal);
    }

    public static void ImportMapForMiniMap(string mapName)
    {
        string[,] lines = LoadMapLaout.MapLayout(mapName);

        //Object prefabTile = AssetDatabase.LoadAssetAtPath("Assets/TheDice/Prefabs/BoardTile.prefab", typeof(GameObject));	
        Object prefabTile = Resources.Load("Prefabs/Ingame/BoardTile") as GameObject;
        float initial_x = -440f;
        float initial_y = -300f;
        int initialDepth = 1;
        float tile_x = initial_x;
        float tile_y = initial_y;
        float tile_z = 0;
        int id_count = 1;

        //string[,] grid = CSVReader.SplitCsvGrid(textAsset.text);

        //int maxGridX = grid.GetUpperBound(0);

        //glog.debug ("bound x="+maxGridX);	
        //glog.debug ("bound y="+grid.GetUpperBound(1));		
        glog.debug("textattset " + mapName);
        boardDic.Clear();
        emptyParent = null;
        PathManager pathManager = null;
        bool bAlreadyBoardCreated = false;
        GameObject pathMgrObj = GameObject.FindGameObjectWithTag("Path Manager");
        if (pathMgrObj != null)
        {
            bAlreadyBoardCreated = true;
            pathManager = pathMgrObj.GetComponent<PathManager>();
            emptyParent = pathMgrObj.transform.parent.gameObject;
        }
        else
        {
            emptyParent = new GameObject();
            //emptyParent = LTPrefabManager.InstantiatePrefab(PrefabTypes.Panel_MiniMap, Vector3.zero, Quaternion.identity);
            //emptyParent = NGUITools.CreateUI(minimapObject.transform, false, LayerMask.NameToLayer("Default")).gameObject;
            emptyParent.AddComponent<MiniMapManager>();
            emptyParent.name = mapName + "_Mini";

            GameObject go = new GameObject();
            pathManager = go.AddComponent<PathManager>();
            go.name = "PathManager";
            go.tag = "Path Manager";
            go.transform.parent = emptyParent.transform;
        }

        //string [] lines =   textAsset.text.Split("\n"[0]); 
        glog.debug(" upperbound  " + lines.GetUpperBound(0) + "    " + lines.GetUpperBound(1));

        //pathManager.nMaxY = lines.GetUpperBound(1) + 2;
        pathManager.nMaxY = 1;
        int maxGridX = 0;

        for (int y = lines.GetUpperBound(1); y >= 0; y--)
        {
            bool bHasValue = false;
            for (int x = 0; x <= lines.GetUpperBound(0); x++)
            {
                if (lines[x, y] != null && lines[x, y] != "")
                {
                    bHasValue = true;
                    break;
                }
            }
            if (bHasValue)
            {
                pathManager.nMaxY++;
                if (lines.GetUpperBound(0) + 1 > maxGridX)
                    maxGridX = lines.GetUpperBound(0) + 1;

                for (int x = 0; x <= lines.GetUpperBound(0); x++)
                {
                    string strTile = lines[x, y];
                    //if(y==0)
                    //	glog.debug("strTile="+strTile);
                    if (strTile != null && strTile != "")
                    {
                        //Debug.Log(strTile + " - ("+ x + ", " + y +")");

                        GameObject tileObj = null;
                        BoardInfo boardInfo = null;

                        if (bAlreadyBoardCreated)
                        {
                            foreach (Transform child in emptyParent.transform)
                            {
                                BoardTile bt = child.gameObject.GetComponent<BoardTile>();
                                if (bt != null && bt.boardInfo.id == id_count)
                                {
                                    tileObj = bt.gameObject;
                                    tileObj.GetComponent<BoardTile>().boardInfo.Clear();
                                    tileObj.GetComponent<BoardTile>().isMiniMap = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            //							tileObj = Instantiate(prefabTile) as GameObject;
                            tileObj = new GameObject();
                            //UITexture tex = tileObj.AddComponent<UITexture>();
                            //tex.material = Resources.Load("MiniMapTile_Temp_Mat") as Material;
                            //tex.mainTexture = Resources.Load("MiniMapTile_Temp") as Texture2D;
                            //tileObj.transform.localScale = new Vector3(0.35f, 0.35f, 0.35f);

                            boardInfo = tileObj.AddComponent<BoardTile>().boardInfo;
                            if (boardInfo == null)
                            {
                                tileObj.GetComponent<BoardTile>().boardInfo = new BoardInfo();
                                boardInfo = tileObj.GetComponent<BoardTile>().boardInfo;
                                tileObj.GetComponent<BoardTile>().isMiniMap = true;
                            }
                            if (boardInfo.pathInfo == null)
                                boardInfo.pathInfo = new List<PathInfo>();
                            boardInfo.pathInfo.Add(new PathInfo());
                            boardInfo.pathInfo.Add(new PathInfo());

                        }

                        tileObj.name = "BoardTile_" + id_count.ToString();
                        tileObj.transform.position = new Vector3(tile_x, tile_y, tile_z);
                        boardInfo = tileObj.GetComponent<BoardTile>().boardInfo;
                        boardDic.Add(id_count, tileObj.GetComponent<BoardTile>());
                        pathManager.boardCount = id_count;
                        boardInfo.id = id_count++;
                        boardInfo.index_x = x + 1;
                        boardInfo.index_y = y + 1;


                        tileObj.transform.parent = emptyParent.transform;

                        emptyParent.GetComponent<MiniMapManager>().tileList.Add(tileObj.GetComponent<BoardTile>());

                        //tk2dSprite sprite = tileObj.GetComponent<tk2dSprite>();	
                        //sprite.color = new Color(255,255,255,255);
                        UISprite sprite = tileObj.AddComponent<UISprite>();
                        GameObject miniMapTileObject = Resources.Load("Atlas/MiniMapTile") as GameObject;
                        //GameObject miniMapTileObject = Resources.Load("Prefabs/EffectTestTrigger") as GameObject;
                        if (miniMapTileObject == null) Debug.LogError("miniMapTileObject is null");
                        sprite.atlas = miniMapTileObject.GetComponent<UIAtlas>();
                        sprite.depth = initialDepth--;
                        string trimedStr = strTile.Trim(new char[] { '\"', ' ', '\r' });

                        string[] commandToken = trimedStr.Split(';');

                        string tilename = commandToken[0];

                        boardInfo.tilename = CBoardDataManager.Instance.GetBoardType(tilename);
                        if (boardInfo.tilename == BoardInfo.TileName.None)
                        {
                            if (y == 0)
                            {
                                tilename = tilename.Remove(tilename.Length - 1);
                                boardInfo.tilename = CBoardDataManager.Instance.GetBoardType(tilename);
                                if (boardInfo.tilename == BoardInfo.TileName.None)
                                    Debug.LogError("tilename none  " + tilename + "  x=" + (x + 1) + "  y=" + (y + 1));
                            }
                            else
                                Debug.LogError("tilename none  " + tilename + "  x=" + (x + 1) + "  y=" + (y + 1));
                        }

                        if (commandToken.Length > 1)
                        {
                            boardInfo.command = commandToken[1].Trim(new char[] { ' ', '\r' });
                            string[] tokens = boardInfo.command.Split(new char[] { '(', ',', ')' });
                            ParseTokens(boardInfo, tokens);
                        }

                        //for several modify_team_param parse twice
                        if (commandToken.Length > 2)
                        {
                            string cmd = commandToken[2].Trim(new char[] { ' ', '\r' });
                            string[] tokens = cmd.Split(new char[] { '(', ',', ')' });
                            ParseTokens(boardInfo, tokens);
                        }

                        if (tilename.StartsWith("road_start"))
                        {
                            boardInfo.isStart = true;
                            startBoard = tileObj.GetComponent<BoardTile>();
                            Vector3 camPos = Camera.main.transform.position;
                            camPos.x = tile_x;
                            camPos.y = tile_y;
                            Camera.main.transform.position = camPos;
                        }
                        else if (tilename.StartsWith("road_end") || tilename.StartsWith("road_goal"))
                        {
                            boardInfo.isGoal = true;
                        }

                        BoardTile.SetModelName(sprite, boardInfo.tilename);

                        tile_z += z_order_offset;
                    }
                    else
                    {
                        initialDepth--;
                        //Debug.Log("this position is empty : (" + tile_x + " , " + tile_y + ")");
                        //pathManager.boartTiles[x,y] = null;
                    }

                    //tile_x += 0.295819f;  // for height 720
                    //tile_y += 0.150303f;  // for height 720

                    tile_x += 30f;
                    tile_y += 16f;
                }

                initial_x += -30f;
                initial_y += 16f;
                initialDepth = -pathManager.nMaxY;
                tile_x = initial_x;
                tile_y = initial_y;
            }
        }

        pathManager.nMaxX = maxGridX + 1;
        //glog.debug ("pathMrg board: "+pathManager.boartTiles.GetUpperBound(0)+" "+pathManager.boartTiles.GetUpperBound(1) );
        glog.debug("total created=" + (id_count - 1));

        GameObject miniMapTileObject2 = Resources.Load("Atlas/MiniMapTile") as GameObject;
        for (int k = 1; k < 5; k++)
        {
            GameObject pawn = new GameObject();
            pawn.name = "pawn_" + k;
            UISprite pawnSprite = pawn.AddComponent<UISprite>();
            pawnSprite.atlas = miniMapTileObject2.GetComponent<UIAtlas>();
            pawnSprite.spriteName = "minipointer_" + k;
            pawnSprite.depth = 2;
            pawnSprite.MakePixelPerfect();
            pawn.transform.parent = emptyParent.transform;
            pawn.transform.localScale = Vector3.one;
        }
    }

    public static void ParseError()
    {
        int[] aa = null;
        aa[0] = 1;
    }

    public static void ParseTokens(BoardInfo boardInfo, string[] command)
    {
        for (int i = 0; i < command.Length; i++)
        {
            command[i] = command[i].Trim();
        }
        boardInfo.tileEffectType = tileEffectMap[command[0]];
        if (command[0] == "teleport_to_tile")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.TeleportToTile;
            int index_x = int.Parse(command[1]);
            int index_y = int.Parse(command[2]);
            //glog.debug ("parse teleport xy "+index_x+ "  "+index_y);
            boardInfo.isTeleport = true;
            boardInfo.teleport_x = index_x;
            boardInfo.teleport_y = index_y;
            boardInfo.tileEffectValue = index_x;
            boardInfo.tileEffectValue_2 = index_y;
        }
        else if (command[0] == "modify_tile_height")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.ModifyTileHeight;
            boardInfo.tileEffectValue = int.Parse(command[1]);
        }
        else if (command[0] == "modify_tile_condition")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.ModifyTileCondition;
            boardInfo.paramString1 = command[1];
            boardInfo.tileEffectValue = int.Parse(command[2]);
        }
        else if (command[0] == "abnormal_delete")
        {
        }
        else if (command[0] == "abnormal_dispell")
        {
        }
        else if (command[0] == "set_tile_effect")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.SetTileEffect;
        }
        else if (command[0] == "get_stop_effect")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.GetStopEfffect;
            boardInfo.targetTileToEffect = tileEffectMap[command[1]];
        }
        else if (command[0] == "modify_team_param")
        {
            SetModTeamParam(boardInfo, command[1], int.Parse(command[2]));

        }
        else if (command[0] == "teleport_to_player")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.TeleportToPlayer;
            SetEffectTarget(command[1], boardInfo);
        }
        else if (command[0] == "teleport_switch")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.TeleportSwitch;
            SetEffectTarget(command[1], boardInfo);
        }
        else if (command[0] == "event_jump")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.EventJump;
            boardInfo.tileEffectValue = int.Parse(command[1]);
            boardInfo.tileEffectValue_2 = int.Parse(command[2]);
        }
        else if (command[0] == "move_extend")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.MoveExtend;
            boardInfo.tileEffectValue = int.Parse(command[1]);
        }
        else if (command[0] == "heal")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.Heal;
            SetEffectTarget(command[1], boardInfo);
            if (command.Length > 2)
                boardInfo.tileEffectValue = int.Parse(command[2]);
        }
        else if (command[0] == "damage")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.Damage;
            SetEffectTarget(command[1], boardInfo);
            if (command.Length > 2)
                boardInfo.tileEffectValue = int.Parse(command[2]);
        }
        else if (command[0] == "resurrect")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.Resurrect;
            SetEffectTarget(command[1], boardInfo);
        }
        else if (command[0] == "bind")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.Bound;
            boardInfo.tileEffectValue = int.Parse(command[1]);
        }
        else if (command[0] == "add_item_temp")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.AddItem;
            //			if(command[1] == "potion_hp_01")
            //				boardInfo.addItemType = BoardInfo.AddItemType.Potion_hp;
            //			else if(command[1] == "potion_resurrect_01")
            //				boardInfo.addItemType = BoardInfo.AddItemType.Potion_resurrect;
            //			else if(command[1] == "cash_coin")
            //				boardInfo.addItemType = BoardInfo.AddItemType.Cash_coin;
            //			else if(command[1] == "game_coin")
            //				boardInfo.addItemType = BoardInfo.AddItemType.Game_coin;
            //			else

            boardInfo.tilename = BoardInfo.TileName.road_item_01; // 아이템타일 강제로 넣어주자

            boardInfo.paramString1 = command[1];
            boardInfo.tileEffectValue = int.Parse(command[2]);
        }
        else if (command[0] == "loot_item_temp")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.LootItem;
            boardInfo.tileEffectValue = int.Parse(command[1]);
        }
        else if (command[0] == "ignore_pass_effect")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.IgnorePassEffect;
            boardInfo.targetTileToEffect = tileEffectMap[command[1]];
        }
        else if (command[0] == "spawn_decoy")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.SpawnDecoy;
        }
        else if (command[0] == "spawn_trap")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.SpawnTrap;
            boardInfo.paramString1 = command[1];
            boardInfo.tileEffectValue = int.Parse(command[2]);
        }
        else if (command[0] == "spawn")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.Spawn;
            boardInfo.paramString1 = command[1];
            if (command.Length > 2)
            {
                if (command[2] != "")
                    boardInfo.tileEffectValue = int.Parse(command[2]);
                else
                    boardInfo.tileEffectValue = 1;
            }
            else
                boardInfo.tileEffectValue = 1;
        }
        else if (command[0] == "dice_delete")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.DiceDelete;
            boardInfo.tileEffectValue = int.Parse(command[1]);
            SetDiceEffectTarget(command[2], boardInfo);
        }
        else if (command[0] == "dice_add")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.DiceAdd;
            boardInfo.tileEffectValue = int.Parse(command[1]);
            SetDiceEffectTarget(command[2], boardInfo);
        }
        else if (command[0] == "dice_switch")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.DiceSwitch;
            boardInfo.tileEffectValue = int.Parse(command[1]);
            SetDiceEffectTarget(command[2], boardInfo);
            SetDiceEffectTarget2(command[3], boardInfo);
        }
        else if (command[0] == "sleep")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.Sleep;
            boardInfo.tileEffectValue = int.Parse(command[1]);
        }
        else if (command[0] == "extra_turn")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.ExtraTurn;
            boardInfo.tileEffectValue = int.Parse(command[1]);
        }
        else if (command[0] == "case_mp_recover")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.CaseMPRecover;
            boardInfo.paramString1 = command[1];
            boardInfo.tileEffectValue = int.Parse(command[2]);
        }
        else if (command[0] == "random_effect")
        {
            boardInfo.paramString1 = command[1];
        }
        else if (command[0] == "spwan_boss")
        {
            boardInfo.paramString1 = command[1];
            if (command.Length > 2)
            {
                if (command[2] != "")
                    boardInfo.tileEffectValue = int.Parse(command[2]);
                else
                    boardInfo.tileEffectValue = 1;
            }
            else
                boardInfo.tileEffectValue = 1;
        }
        else if (command[0] == "damage_random")
        {
            //boardInfo.tileEffectType = BoardInfo.TileEffectType.Damage;
            SetEffectTarget(command[1], boardInfo);
            if (command.Length > 3)
            {
                boardInfo.tileEffectValue = int.Parse(command[2]);
                boardInfo.tileEffectValue_2 = int.Parse(command[3]);
            }
        }
        else
            ParseError();
    }

    public static void SetModTeamParam(BoardInfo boardInfo, string cmd, int applyValue)
    {
        if (cmd == "move")
            boardInfo.modify_team_param.Add(new ModTeamParam(AbnormalType.MODIFY_TEAM_PARAM_MOVE, applyValue));
        else if (cmd == "move_critical_rate")
            boardInfo.modify_team_param.Add(new ModTeamParam(AbnormalType.MODIFY_TEAM_PARAM_MOVE_PROB, applyValue));
        else if (cmd == "avoid")
            boardInfo.modify_team_param.Add(new ModTeamParam(AbnormalType.MODIFY_TEAM_PARAM_AVOID, applyValue));
        else if (cmd == "avoid_critical_rate")
            boardInfo.modify_team_param.Add(new ModTeamParam(AbnormalType.MODIFY_TEAM_PARAM_AVOID_PROB, applyValue));
        else if (cmd == "block")
            boardInfo.modify_team_param.Add(new ModTeamParam(AbnormalType.MODIFY_TEAM_PARAM_BLOCK, applyValue));
        else if (cmd == "block_critical_rate")
            boardInfo.modify_team_param.Add(new ModTeamParam(AbnormalType.MODIFY_TEAM_PARAM_BLOCK_PROB, applyValue));
        else if (cmd == "chase")
            boardInfo.modify_team_param.Add(new ModTeamParam(AbnormalType.MODIFY_TEAM_PARAM_CHASE, applyValue));
        else if (cmd == "chase_critical_rate")
            boardInfo.modify_team_param.Add(new ModTeamParam(AbnormalType.MODIFY_TEAM_PARAM_CHASE_PROB, applyValue));
        else
            ParseError();
    }

    public static void SetDiceEffectTarget(string target, BoardInfo boardInfo)
    {
        if (target == "low")
        {
            boardInfo.diceTargetType = BoardInfo.DiceTargetType.Low;
        }
        else if (target == "high")
        {
            boardInfo.diceTargetType = BoardInfo.DiceTargetType.High;
        }
        else if (target == "random")
        {
            boardInfo.diceTargetType = BoardInfo.DiceTargetType.Random;
        }
        else
            ParseError();
    }

    public static void SetDiceEffectTarget2(string target, BoardInfo boardInfo)
    {
        if (target == "low")
        {
            boardInfo.diceTargetType2 = BoardInfo.DiceTargetType.Low;
        }
        else if (target == "high")
        {
            boardInfo.diceTargetType2 = BoardInfo.DiceTargetType.High;
        }
        else if (target == "random")
        {
            boardInfo.diceTargetType2 = BoardInfo.DiceTargetType.Random;
        }
        else
            ParseError();
    }

    public static void SetEffectTarget(string target, BoardInfo boardInfo)
    {
        if (target == "all")
        {
            boardInfo.tileEffectTarget = BoardInfo.TileEffectTarget.All;
        }
        else if (target == "leader")
        {
            boardInfo.tileEffectTarget = BoardInfo.TileEffectTarget.Leader;
        }
        else if (target == "random")
        {
            boardInfo.tileEffectTarget = BoardInfo.TileEffectTarget.Random;
        }
        else if (target == "percent")
        {
            boardInfo.tileEffectTarget = BoardInfo.TileEffectTarget.percent;
        }
        else if (target == "point")
        {
            boardInfo.tileEffectTarget = BoardInfo.TileEffectTarget.point;
        }
        else
            ParseError();
    }

    //	public static void SetTileName(string tilename, tk2dSprite sprite)
    //	{
    //		string modelname = "tile_" + tilename;
    //		if(tilename == "road_common")
    //		{
    //			int cn = Random.Range(0,2) + 1;
    //			sprite.SetSprite(tilename+"_0"+cn.ToString());		
    //		}
    //		
    //	}


    //  Unity.exe -quit -batchmode -executeMethod ExportManager.ImportStage1
    //[MenuItem("TheDice/Import/map_prototype")]
    /*
    public static void ImportStage1()
    {
        //Application.LoadLevel ("Stage1");
		
        Object prefabTile = AssetDatabase.LoadAssetAtPath("Assets/TheDice/Prefabs/BoardTile.prefab", typeof(GameObject));		
        TextAsset textAsset = (TextAsset) AssetDatabase.LoadAssetAtPath("Assets/TheDice/TextAsset/stage1.txt", typeof(TextAsset) );
		
        float initial_x = start_x;
        float initial_y = start_y;
        float tile_x = initial_x;
        float tile_y = initial_y;
        float tile_z = 0;
        int id_count = 1;
		
        string[,] grid = CSVReader.SplitCsvGrid(textAsset.text);
		
        int maxGridX = grid.GetUpperBound(0)-1; // �??�에 �??�트링이 ?�나??추�??�어??-1???�줌
		
        glog.debug ("bound x="+maxGridX);	
        glog.debug ("bound y="+grid.GetUpperBound(1));		
		
		
		
        emptyParent = new GameObject();
        emptyParent.name = "BoardCreated";
		
        GameObject go = new GameObject();
        PathManager pathManager = go.AddComponent<PathManager>();
        go.name = "PathManager";
        go.tag = "Path Manager";
        go.transform.parent = emptyParent.transform;
		
        pathManager.nMaxX = maxGridX;
        pathManager.nMaxY = grid.GetUpperBound(1);
		
        int[,] boardExistId = new int[maxGridX, grid.GetUpperBound(1)];
        for(int y=0; y< grid.GetUpperBound(1); y++)
        {
            for(int x=0; x< maxGridX; x++)
            {
                boardExistId[x,y] = -1;
            }
        }
        //pathManager.InitBoardTiles(maxGridX, grid.GetUpperBound(1) );
        BoardTile startBoard = null;
        for (int y = grid.GetUpperBound(1)-1; y >=0; y--) {	
			
            for (int x = 0; x < maxGridX; x++) {
                string strTile = grid[x,y];
                //if(y==0)
                //	glog.debug("strTile="+strTile);
                if(strTile != "0") {
                    GameObject tileObj = Instantiate(prefabTile) as GameObject;
                    tileObj.name = "BoardTile_"+id_count.ToString();
                    tileObj.transform.position = new Vector3(tile_x, tile_y, tile_z);
                    BoardInfo boardInfo = tileObj.GetComponent<BoardTile>().boardInfo;
                    pathManager.boardCount = id_count;
                    boardInfo.id = id_count++;
                    boardInfo.index_x = x;
                    boardInfo.index_y = y;
                    //boardInfo.nearBoards = new int[4];
					
                    boardExistId[x,y] = boardInfo.id;
                    //pathManager.boartTiles[x,y] = tileObj.GetComponent<BoardTile>();
					
                    tileObj.transform.parent = emptyParent.transform;
					
                    if(strTile == "road_normal") {
						
                    }
                    else if(strTile == "road_start_01") {
                        tk2dSprite sprite = tileObj.GetComponent<tk2dSprite>();
                        sprite.color = new Color(213/255.0f, 242/255.0f, 206/255.0f, 255.0f);
                        boardInfo.isStart = true;
                        Vector3 camPos = Camera.main.transform.position;
                        camPos.x = tile_x;
                        camPos.y = tile_y;
                        Camera.main.transform.position = camPos;
                    }
                    else if(strTile == "road_end_01") {
                        tk2dSprite sprite = tileObj.GetComponent<tk2dSprite>();
                        sprite.color = new Color(242/255.0f, 157/255.0f, 169/255.0f, 255.0f);						
                        boardInfo.isGoal = true;
                    }
                    tile_z += z_order_offset;
                }
                else
                {
                    //pathManager.boartTiles[x,y] = null;
                }
                tile_x += 0.2892421f;//0.3704f;
                tile_y += 0.1537679f;//0.1372f;
				
            }
			
            initial_x += -0.2892421f;//0.368557f;
            initial_y += 0.1537679f;//0.20531f;
            tile_x = initial_x;
            tile_y = initial_y;
        }		
	
        //glog.debug ("pathMrg board: "+pathManager.boartTiles.GetUpperBound(0)+" "+pathManager.boartTiles.GetUpperBound(1) );
        glog.debug ("total created="+(id_count-1));		
		
        //?�접????�� ?�보 추�?
		
//		int nNearIndex = 0;
//		for(int i=0; i< emptyParent.transform.GetChildCount(); i++)
//		{
//			nNearIndex = 0;
//			BoardTile btile = emptyParent.transform.GetChild(i).gameObject.GetComponent<BoardTile>();
//			if(btile == null)
//				continue;
//			BoardInfo binfo = emptyParent.transform.GetChild(i).gameObject.GetComponent<BoardTile>().boardInfo;
//
//			int ix = binfo.index_x;
//			int iy = binfo.index_y;
//			if( ix -1 >=0 && boardExistId[ix-1,iy] != -1)
//				binfo.nearBoards[nNearIndex++] = boardExistId[ix-1,iy];
//			if( ix +1 < pathManager.nMaxX && boardExistId[ix+1,iy] != -1)
//				binfo.nearBoards[nNearIndex++] = boardExistId[ix+1,iy];
//			if( iy -1 >=0 && boardExistId[ix,iy-1] != -1) 
//				binfo.nearBoards[nNearIndex++] = boardExistId[ix,iy-1];
//			if( iy +1 < pathManager.nMaxY && boardExistId[ix,iy+1] != -1)
//				binfo.nearBoards[nNearIndex++] = boardExistId[ix,iy+1];
//			
//		}
		
				
        //EditorApplication.SaveScene();
        //EditorApplication.Exit(0);		
    }	*/


    /*
    public static void ExportBoardNoQuit()
    {
        //string path = @"c:\MyTest.txt";
		
        // This text is added only once to the file. 
        //if (!File.Exists(path))
        //{
            // Create a file to write to. 
        //    string createText = "Hello and Welcome\r\n";
        //    File.WriteAllText(path, createText);
        //}

        BoardInfoContainer binfoContainer = new BoardInfoContainer();
        BoardTile[] boards = FindObjectsOfType(typeof(BoardTile)) as BoardTile[];
        //binfoContainer.boardInfos = new BoardInfo[boards.Length];
        int i=0;
        foreach (BoardTile board in boards) {
            //binfoContainer.boardInfos[i++] = board.boardInfo;
            binfoContainer.boardInfos.Add( board.boardInfo );
            //string appendText = "id="+board.id+"  isStart="+board.isStart+"  type="+board.boardType+"\r\n";
           // File.AppendAllText(path, appendText);
        }		
		
        string xmlPath = @"c:\TheDice\Work\trunk\xml\map_prototype.xml";
        binfoContainer.Save(xmlPath);		
    }
    */
    public static BoardInfoContainer GetBoardInfo()
    {
        BoardInfoContainer binfoContainer = new BoardInfoContainer();
        BoardTile[] boards = FindObjectsOfType(typeof(BoardTile)) as BoardTile[];
        //binfoContainer.boardInfos = new BoardInfo[boards.Length];
        int i = 0;
        foreach (BoardTile board in boards)
        {
            binfoContainer.boardInfos.Add(board.boardInfo);
        }
        return binfoContainer;
    }

    public static void ImportPath(string mapname)
    {
        string xmlPath = Application.dataPath + "/../../xml/map_" + mapname + ".xml";
        BoardInfoContainer binfoContainer = BoardInfoContainer.Load(xmlPath);
        BoardTile[] boards = FindObjectsOfType(typeof(BoardTile)) as BoardTile[];
        foreach (BoardInfo binfo in binfoContainer.boardInfos)
        {
            foreach (BoardTile board in boards)
            {
                //if(binfo.index_x == board.boardInfo.index_x && binfo.index_y == board.boardInfo.index_y) {	
                if (binfo.id == board.boardInfo.id)
                {
                    //					board.boardInfo.forwardBoards.Clear();
                    //					board.boardInfo.backBoards.Clear();
                    //					board.boardInfo.ratioToGoal.Clear();
                    //					foreach( List<int> list in binfo.forwardBoards)
                    //					{
                    //						board.boardInfo.forwardBoards.Add ( list );
                    //					}
                    //					foreach( List<int> list in binfo.backBoards)
                    //					{
                    //						board.boardInfo.backBoards.Add ( list );
                    //					}
                    //					foreach( float r in binfo.ratioToGoal)
                    //					{
                    //						board.boardInfo.ratioToGoal.Add ( r );
                    //					}
                }
            }
        }
    }

    //	[MenuItem("TheDice/TestLoad/map_prototype")]
    //	public static void TestLoadBoardInfo()
    //	{
    //		string xmlPath = @"E:\photon\deploy\Policy\map_prototype.xml";
    //		BoardInfoContainer binfoContainer = BoardInfoContainer.Load (xmlPath);
    //		foreach( BoardInfo binfo  in binfoContainer.boardInfos)
    //		{
    //			glog.debug ("binfo="+binfo.id+" "+binfo.index_x+ " "+binfo.index_y);
    //		}
    //	}	

    public static void CheckPath(BoardTile tile)
    {
        pathTemp.Add(tile);
        if (tile.nextBoards.Count == 0 || (tile.boardInfo.isStart && isCheckPathStarted))
        {
            MultiListPath pathToAdd = new MultiListPath();

            foreach (BoardTile t in pathTemp)
                pathToAdd.tileList.Add(t);
            //glog.debug ("path added "+pathToAdd.tileList.Count);
            paths.Add(pathToAdd);
            pathTemp.Remove(tile);
            return;
        }
        isCheckPathStarted = true;
        foreach (BoardTile nextTile in tile.nextBoards)
        {
            CheckPath(nextTile);
        }
        pathTemp.Remove(tile);
    }

    static BoardTile GetBoardTile(int id)
    {
        if (boardDic.ContainsKey(id))
            return boardDic[id];
        else
        {
            return null;
        }
    }

    //	[MenuItem("TheDice/Util_CalcutateRatioGoal")]
    public static void CalcutateRatioGoal(int pathIndex)
    {
        glog.debug("pathIndex=" + pathIndex);
        if (emptyParent == null)
        {
            GameObject pathMgrObj = GameObject.FindGameObjectWithTag("Path Manager");
            if (pathMgrObj != null)
            {
                emptyParent = pathMgrObj.transform.parent.gameObject;
            }
        }

        if (boardDic.Count == 0)
        {
            foreach (Transform child in emptyParent.transform)
            {
                BoardTile bt = child.gameObject.GetComponent<BoardTile>();
                if (bt != null)
                {
                    boardDic.Add(bt.boardInfo.id, bt);
                }
            }
        }

        BoardTile tempGoalBoard = null;
        BoardTile tempStartBoard = null;
        foreach (Transform child in emptyParent.transform)
        {
            BoardTile bt = child.gameObject.GetComponent<BoardTile>();
            if (bt != null)
            {
                bt.nextBoards.Clear();

                if (bt.boardInfo.isGoal)
                    tempGoalBoard = bt;
                if (bt.boardInfo.isStart)
                    tempStartBoard = bt;

                foreach (int nForwardId in bt.boardInfo.pathInfo[pathIndex].forwardBoards)
                {
                    bt.nextBoards.Add(GetBoardTile(nForwardId));
                }
            }
        }
        if (tempGoalBoard == null)
            tempGoalBoard = tempStartBoard;

        pathTemp.Clear();
        paths.Clear();
        isCheckPathStarted = false;
        if (pathIndex == 1)
            CheckPath(tempGoalBoard);
        else
            CheckPath(tempStartBoard);

        foreach (Transform child in emptyParent.transform)
        {
            BoardTile bt = child.gameObject.GetComponent<BoardTile>();
            if (bt != null)
            {
                int lengthPath = 0;
                MultiListPath selectedPath = new MultiListPath();
                foreach (MultiListPath path in paths)
                {
                    if (path.tileList.Contains(bt))
                    {
                        if (path.tileList.Count > lengthPath)
                        {
                            lengthPath = path.tileList.Count;
                            selectedPath = path;
                        }
                    }
                }
                bt.tileTotal = selectedPath.tileList.Count;
                int indexOfBT = selectedPath.tileList.IndexOf(bt);
                bt.tileRemain = bt.tileTotal - (indexOfBT + 1);

                bt.boardInfo.pathInfo[pathIndex].ratioToGoal = indexOfBT / (float)(bt.tileTotal - 1);
				if(pathIndex==1)
				{
					if(bt.boardInfo.isGoal )
						bt.boardInfo.pathInfo[pathIndex].IsStartBoard = true;
					if(bt.boardInfo.isStart)
						bt.boardInfo.pathInfo[pathIndex].IsGoalBoard = true;
				}
				else
				{
					if(bt.boardInfo.isStart )
						bt.boardInfo.pathInfo[pathIndex].IsStartBoard = true;
					if(bt.boardInfo.isGoal)
						bt.boardInfo.pathInfo[pathIndex].IsGoalBoard = true;
				}
                bt.nextBoards.Clear();
            }
        }

    }

    public static bool ExportMap(string mapName)
    {
        BoardInfoContainer binfoContainer = GetBoardInfo();
        string xmlPath = @"..\xml\map_" + mapName + ".xml";
        binfoContainer.Save(xmlPath);
		
		MapBoardInfo mapBoardInfo = FindObjectOfType(typeof(MapBoardInfo)) as MapBoardInfo;
		if(mapBoardInfo==null)
		{
			GameObject go = new GameObject();
			go.name = "board_map_"+mapName;
			mapBoardInfo = go.AddComponent<MapBoardInfo>();
		}

		mapBoardInfo.boardInfoList.Clear();
		foreach(BoardInfo binfo in binfoContainer.boardInfos)
			mapBoardInfo.boardInfoList.Add ( binfo);

		PathManager pathManager = FindObjectOfType(typeof(PathManager)) as PathManager;
		if(pathManager!=null)
		{
			mapBoardInfo.nMaxX = pathManager.nMaxX;
			mapBoardInfo.nMaxY = pathManager.nMaxY;
			mapBoardInfo.boardCount = pathManager.boardCount;
		}
		else
		{
			Debug.LogError("pathmanager does not exist");
			return false;
		}

		UnityEngine.Object newPrefab = PrefabUtility.CreateEmptyPrefab("Assets/Resources/Prefabs/Board/"+mapBoardInfo.gameObject.name+".prefab");
		PrefabUtility.ReplacePrefab(mapBoardInfo.gameObject, newPrefab, ReplacePrefabOptions.ConnectToPrefab);
		AssetDatabase.SaveAssets();
		GameObject.DestroyImmediate(mapBoardInfo.gameObject);
		return true;
    }

    //	[MenuItem("TheDice/Export_map_prototype")]
    //	public static void ExportMap_proto()
    //	{
    //		BoardInfoContainer binfoContainer = GetBoardInfo();
    //		string xmlPath = @"c:\TheDice\Work\trunk\xml\map_prototype.xml";
    //		binfoContainer.Save(xmlPath);
    //	}
    //	
    //	[MenuItem("TheDice/Export_map_demo01")]
    //	public static void ExportMap_demo01()
    //	{
    //		BoardInfoContainer binfoContainer = GetBoardInfo();
    //		string xmlPath = @"c:\TheDice\Work\trunk\xml\map_demo01.xml";
    //		binfoContainer.Save(xmlPath);
    //	}	
    //	
    //	[MenuItem("TheDice/Export_map_demo02")]
    //	public static void ExportMap_demo02()
    //	{
    //		BoardInfoContainer binfoContainer = GetBoardInfo();
    //		string xmlPath = @"c:\TheDice\Work\trunk\xml\map_demo02.xml";
    //		binfoContainer.Save(xmlPath);
    //	}
    //	
    //	[MenuItem("TheDice/Export_map_m1_1")]
    //	public static void ExportMap_m1_1()
    //	{
    //		BoardInfoContainer binfoContainer = GetBoardInfo();
    //		string xmlPath = @"c:\TheDice\Work\trunk\xml\map_m1_1.xml";
    //		binfoContainer.Save(xmlPath);
    //	}	

    /*	
    [MenuItem("TheDice/Create background")]
    public static void CreateBackground()
    {
        Material newMaterial = (Material) AssetDatabase.LoadAssetAtPath("Assets/TheDice/Materials/backTile.mat", typeof(Material) );
        float gridSize = 15.0f;
        int xLength = 2;
        int yLength = 2;
	
		
        Color[] colors;		
        GameObject backGo = new GameObject();
        backGo.transform.position = new Vector3(-7.964561f, -1.376864f, 3.0f);
        backGo.transform.localScale = new Vector3(1.066013f, 0.5735569f, 0.5735569f);
        backGo.name = "background";
		
        MeshFilter mf = (MeshFilter)backGo.AddComponent("MeshFilter");
        backGo.AddComponent("MeshRenderer");
        Mesh mesh = new Mesh();
	
        mesh.Clear();
		
        // vertices ---------------------------------------------------------------------------------
        ArrayList verts = new ArrayList();
	
        for (int y = 0; y < yLength; ++y)
        {
            for (int x = 0; x < xLength; ++x)
            {
                verts.Add( new Vector3( (x*gridSize), (y*gridSize), backGo.transform.position.z) );
            }
        }

        mesh.vertices = (Vector3[]) verts.ToArray( typeof( Vector3 ) );
	
        // uv's ----------------------------------------------------------------------------------------
        Vector2[] uvs = new Vector2[verts.Count];
	
        for (int i=0;i<uvs.Length;i++) {
            Vector3 v = (Vector3)verts[i];
            uvs[i].x = v.x;
            uvs[i].y = v.y;
        }
        mesh.uv = uvs;
	
        // triangles ---------------------------------------------------------------------------------
        ArrayList tris = new ArrayList();
	
        for (int y = 0; y < yLength-1; ++y)
        {
            for (int x = 0; x < xLength-1; ++x)
            {
                int vertHere = x+(y*xLength);
                int vertAbove = x+((y+1)*xLength);
                tris.Add(vertHere); 
                tris.Add(vertAbove);
                tris.Add(vertAbove+1);
	
                tris.Add(vertHere);
                tris.Add(vertAbove+1);
                tris.Add(vertHere+1);
                //glog.debug(x + "," + y + ": " +
                //	vertHere + "," + vertAbove + "," + (vertAbove+1) + " " +
                //	vertHere + "," + (vertAbove+1) + "," + (vertHere+1));
            }
        }
		
        mesh.triangles = (int[]) tris.ToArray( typeof(int));
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
	
        // vertex colors ------------------------------------------------------------------------------
        glog.debug ("mesh.vertices.Length " + mesh.vertices.Length);
        colors = new Color[mesh.vertices.Length];
	
        for (int i=0;i<mesh.vertices.Length;i++)
        {
            colors[i].r = 1;
            colors[i].g = 1;
            colors[i].b = 1;
            colors[i].a = 1;
        }
        mesh.colors = colors;
		
        mf.sharedMesh = mesh;
        backGo.renderer.castShadows = false;
        backGo.renderer.receiveShadows = false;
        backGo.renderer.material = newMaterial;		
		
    }
    */
    // ?�니???�치 ?�더 �?�� ?�음???�력 ?�다
    // Unity.exe -quit -batchmode -nographics -executeMethod ExportManager.ExportBoard	
    /*public static void ExportBoard()
    {
        Application.LoadLevel ("Stage1");
		
        ExportBoardNoQuit();
		
        EditorApplication.Exit(0);
		
        // Open the file to read from. 
        //string readText = File.ReadAllText(path);
        //glog.debug("readText="+readText);
    }*/



    /*
    public static void LoadExport()
    {
        BoardInfoContainer binfoContainer = new BoardInfoContainer();
        string xmlPath = @"e:\MyTest.xml";
        binfoContainer = BoardInfoContainer.Load(xmlPath);
		
        string path = @"c:\MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to. 
            string createText = "load xml test\r\n";
            File.WriteAllText(path, createText);
        }		
		
        foreach (BoardInfo boardInfo in binfoContainer.boardInfos) {
            string appendText = "id="+boardInfo.id+"  isStart="+boardInfo.isStart+"  type="+boardInfo.boardType+"\r\n";
            File.AppendAllText(path, appendText);
        }
		
        EditorApplication.Exit(0);
    }
    */
    /*
    public static void TestApplyBoardinfo()
    {
        BoardInfoContainer binfoContainer = new BoardInfoContainer();
        string xmlPath = @"e:\MyTest.xml";
        binfoContainer = BoardInfoContainer.Load(xmlPath);
		
        Application.LoadLevel ("Stage1");
		
        BoardTile[] boardList = FindObjectsOfType(typeof(BoardTile)) as BoardTile[];
        glog.debug ("boardList ="+boardList.Length);
        glog.debug ("boardinfos="+binfoContainer.boardInfos.Count);
        foreach (BoardTile board in boardList) {
            foreach (BoardInfo boardInfo in binfoContainer.boardInfos) {
                if(boardInfo.id == board.boardInfo.id)
                {
                    glog.debug ("apply "+boardInfo.id+ "  type="+boardInfo.tileEffectType);
                    board.boardInfo = boardInfo;
                    break;
                }
            }           
        }		

		
        EditorApplication.SaveScene();
        EditorApplication.Exit(0);
    }
    */

}
#endif